const mongoose = require("mongoose");

mongoose.connect("mongodb://127.0.0.1:27017/bilibili");
mongoose.set("strictQuery", true);
mongoose.connection.once("open", () => {
  console.log("连接成功");
  const BookSchema = new mongoose.Schema({
    name: {
      type: String,
      required: true, // 属性不为空
      unique: true, // 唯一值（只有新的集合才有效）
    },
    author: {
      type: String,
      default: "匿名",
    },
    price: Number,
    style: {
      type: String,
      enum: ["言情", "城市", "志怪", "恐怖"],
    },
  });

  const BookModel = mongoose.model("books", BookSchema);
  BookModel.create(
    {
      name: "西游记",
      // author: "吴承恩",
      price: 19.9,
      style: "志怪",
    },
    (err, data) => {
      if (err) {
        return console.log(err);
      }
      console.log(data);
      // 关闭数据库连接(项目运行中不会添加)
      // mongoose.disconnect();
    }
  );
});

mongoose.connection.on("error", () => {
  console.log("连接失败");
});

mongoose.connection.on("close", () => {
  console.log("连接关闭");
});
